"""
示例异步任务
"""
from celery_app import celery_app
from motor.motor_asyncio import AsyncIOMotorClient
from config.settings import settings
import asyncio


@celery_app.task(name="tasks.example.add")
def add(x: int, y: int) -> int:
    """
    简单的加法任务（示例）
    
    使用方式：
        result = add.delay(4, 6)
        print(result.get())  # 10
    """
    return x + y


@celery_app.task(name="tasks.example.send_email")
def send_email(to: str, subject: str, body: str) -> dict:
    """
    发送邮件任务（示例）
    
    实际生产环境需要配置 SMTP
    """
    print(f"Sending email to {to}: {subject}")
    # 这里应该使用真实的邮件发送逻辑
    # import smtplib
    # ...
    return {
        "status": "sent",
        "to": to,
        "subject": subject
    }


@celery_app.task(name="tasks.example.cleanup_old_audit_logs")
def cleanup_old_audit_logs(days: int = 90) -> dict:
    """
    清理过期审计日志
    
    定时任务，每小时执行一次
    """
    async def _cleanup():
        client = AsyncIOMotorClient(settings.MONGODB_URL)
        db = client[settings.MONGODB_DB_NAME]
        
        from services.audit import AuditService
        audit_service = AuditService(db)
        
        deleted_count = await audit_service.delete_old_logs(days)
        
        client.close()
        return deleted_count
    
    # 在 Celery 中运行异步函数
    loop = asyncio.get_event_loop()
    deleted_count = loop.run_until_complete(_cleanup())
    
    return {
        "status": "completed",
        "deleted_count": deleted_count,
        "days": days
    }


@celery_app.task(name="tasks.example.process_batch_operation")
def process_batch_operation(operation: str, resource_ids: list) -> dict:
    """
    批量操作任务
    
    用于处理批量资源操作
    """
    success_count = 0
    failed_count = 0
    errors = {}
    
    for resource_id in resource_ids:
        try:
            # 这里执行实际的批量操作逻辑
            print(f"Processing {operation} for resource {resource_id}")
            success_count += 1
        except Exception as e:
            failed_count += 1
            errors[resource_id] = str(e)
    
    return {
        "status": "completed",
        "operation": operation,
        "success_count": success_count,
        "failed_count": failed_count,
        "errors": errors
    }


@celery_app.task(
    name="tasks.example.long_running_task",
    bind=True,  # 绑定到任务实例
    max_retries=3  # 最大重试次数
)
def long_running_task(self, task_id: str, duration: int = 10):
    """
    长时间运行的任务示例
    
    展示进度更新和重试机制
    """
    try:
        import time
        
        # 更新任务状态
        self.update_state(
            state='PROGRESS',
            meta={'current': 0, 'total': duration, 'status': '开始处理...'}
        )
        
        for i in range(duration):
            time.sleep(1)
            
            # 更新进度
            self.update_state(
                state='PROGRESS',
                meta={
                    'current': i + 1,
                    'total': duration,
                    'status': f'处理中 {i+1}/{duration}...'
                }
            )
        
        return {
            'status': 'completed',
            'result': f'Task {task_id} completed successfully'
        }
        
    except Exception as exc:
        # 重试任务
        raise self.retry(exc=exc, countdown=60)  # 60秒后重试

